import { _decorator, Button, Component, EditBox, Label, sys } from 'cc';
import { DEBUG } from 'cc/env';
import AudioSetting from 'db://cocos-ext/base/AudioSetting';
import { games, lobby, yy } from 'yycore';

const { ccclass, property } = _decorator;
const STATE_STR = ["未登录", "第三方登陆中", "登陆中", "成功登陆"];
const DEV_DATA_KEY = 'DevLoginInfo';

// 调试登录使用的账号信息
interface DevLoginInfo {
    // 账号
    acc?: string;
    // 密码
    pwd?: string;
    // 默认语言
    language?: string;
    // 是否静音
    mute?: boolean;
}

@ccclass('EasyLoginUI')
export default class EasyLoginUI extends Component {

    // 多语言文本框
    @property(EditBox)
    private readonly LanguageBox: EditBox = null;

    // 音效按钮文本
    @property(Label)
    private readonly txtSound: Label = null;

    // MSG Label
    @property(Label)
    private readonly tipsLabel: Label = null;

    // login Button
    @property(Button)
    private readonly loginBtn: Button = null;

    // ACC EditBox
    @property(EditBox)
    private readonly ACCEditBox: EditBox = null;

    // PWD EditBox
    @property(EditBox)
    private readonly PWDEditBox: EditBox = null;



    onLoad() {
        // 监听登录事件
        yy.event.on(this, lobby.events.LoginLobbyResult, (e: lobby.events.LoginLobbyResult) => {
            this.saveDevLoginInfo();
            if (!this.node.activeInHierarchy) return;

            if (!e.bSucceed) {
                this.loginBtn.interactable = true;
                const msg = `登录失败(${e.errorCode}): ${e.errorDesc}`;
                this.tipsLabel.string = msg;
                DEBUG && console.error(msg);
                return;
            }

            this.tipsLabel.string = STATE_STR[games.LoginState.Logined];
        });
    }

    start() {
        const dev_data: DevLoginInfo = this.getDevLoginInfo();

        // language
        const str = (dev_data.language || 'en').trim().toLowerCase();
        yy.sys.setCurrentLanguage(str);
        this.LanguageBox.string = str;
        DEBUG && console.log('current language:', yy.sys.curLanguage);

        // mute
        const mute = dev_data.mute || false;
        this.setPlatformAudio(mute);

        // 初始化
        this.ACCEditBox.string = dev_data.acc || "";
        this.PWDEditBox.string = dev_data.pwd || "";
        const loginState = lobby.service.getLoginState();
        if (loginState != games.LoginState.Logined) {
            lobby.service.reqLogoutLobby();
        }
        this.tipsLabel.string = '';
    }

    private doLogin() {
        this.tipsLabel.string = STATE_STR[games.LoginState.Logining];
        this.loginBtn.interactable = false;
        lobby.service.reqLoginLobby(this.ACCEditBox.string, this.PWDEditBox.string, true);
        this.node.active = false;
    }

    // 多语言设置更改
    private onLanguageInputEnd() {
        const language = this.LanguageBox.string.trim().toLowerCase() || 'en';
        yy.sys.setCurrentLanguage(language);
        DEBUG && console.log('current language:', yy.sys.curLanguage);
    }

    // 音效设置
    private btnClickedSoundSetting() {
        const curMute: boolean = this.txtSound.string == "OFF";
        this.setPlatformAudio(!curMute);
    }

    // 平台音效设置
    private setPlatformAudio(mute: boolean) {
        if (this.txtSound)
            this.txtSound.string = mute ? 'OFF' : 'ON';

        games.setting.isMute = mute;
        AudioSetting.mute = mute;
    }

    // 获取本地保存的调试登录信息
    private getDevLoginInfo(): DevLoginInfo {
        const dataItem = sys.localStorage.getItem(DEV_DATA_KEY);
        let dev_data: DevLoginInfo;
        if (dataItem) {
            dev_data = JSON.parse(dataItem);
        } else {
            dev_data = { acc: '', pwd: '', language: "en", mute: false };
        }
        return dev_data;
    }
    // 修改本地存储的调试登录信息
    private saveDevLoginInfo() {
        const dev_data: DevLoginInfo = {
            acc: this.ACCEditBox.string,
            pwd: this.PWDEditBox.string,
            language: yy.sys.curLanguage,
            mute: games.setting.isMute
        };

        sys.localStorage.setItem(DEV_DATA_KEY, JSON.stringify(dev_data))
    }

}

